package com.atguigu.gmall.realtime.utils;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.GmallConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.flink.util.IOUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 从 phoenix 中查询数据工具类
 *
 * @author lvbingbing
 * @date 2022-04-01 10:18
 */
@Slf4j
public class PhoenixUtils {

    private static Connection connection;

    private static void initConnection() {
        try {
            // 注册驱动
            Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
            // 获取连接
            connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);
            // 设置操作的表空间
            connection.setSchema(GmallConfig.HBASE_SCHEMA);
        } catch (Exception e) {
            log.error("获取连接失败，失败原因：{}", e);
        }
    }

    public static <T> List<T> queryList(String sql, Class<T> clazz) {
        if (connection == null) {
            initConnection();
        }
        if (connection == null) {
            return Collections.emptyList();
        }
        List<T> resultList = new ArrayList<>();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 创建数据库操作对象
            preparedStatement = connection.prepareStatement(sql);
            // 执行 SQL，获取结果集
            resultSet = preparedStatement.executeQuery();
            // 获取查询结果集的元数据信息
            ResultSetMetaData metaData = resultSet.getMetaData();
            // 处理结果集
            while (resultSet.next()) {
                T instance = clazz.newInstance();
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object columnValue = resultSet.getObject(i);
                    BeanUtils.setProperty(instance, columnName, columnValue);
                }
                resultList.add(instance);
            }
            return resultList;
        } catch (Exception e) {
            log.error("查询数据时出现异常！异常原因：{}", e);
            return Collections.emptyList();
        } finally {
            IOUtils.closeQuietly(resultSet);
            IOUtils.closeQuietly(preparedStatement);
        }
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        List<JSONObject> jsonObjectList = queryList("select * from dim_base_trademark", JSONObject.class);
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;
        log.info("查询耗时：{}ms, 查询结果：{}", costTime, jsonObjectList);
    }
}